const mongoose = require('mongoose');
const jwt=require('jsonwebtoken');
const MongoOrder = require('../models/order');
const MongoProduct = require('../models/product');
const redis = require('redis');
function writeCache(req,result) { 
    const client = redis.createClient(6379, '127.0.0.1')
        client.auth(process.env.REDIS_PWD)//校验密码
    client.on('connect',()=>{
        console.log('写入缓存')
        client.set(req.query.cacheKey,JSON.stringify(result))
    })
}
exports.order_add = (req, res, next) => {
    MongoProduct.findById(req.body.pid).exec().then(result=>{
        //console.log(result)
        if(!result){
            return res.status(404).json({
                message:'no product'
            })
        }
        const decoded =(req.body.isDefuser===1)?jwt.decode(req.headers.token):{};
        const order=new MongoOrder({
            _id:new mongoose.Types.ObjectId(),
            name:decoded.username||req.body.username,
            phone:decoded.phone||req.body.phone,
            address:decoded.address||req.body.address,
            quantity:req.body.quantity,
            product:req.body.pid
        })
        order.save().then(docs=>{
            const amount=result.stock-req.body.quantity;
            console.log(amount);
            if(amount<=0){//库存不够
                return res.status(401).json({
                    message:'no stock'
                })
            }
            res.status(201).json({
                message:'order created',
                orders:docs
            });
            MongoProduct.findByIdAndUpdate(req.body.pid,{$set:{stock:amount}}).exec()//下单后更新库存
        }).catch(err=>{
            res.status(500).json(err)
        })
    }).catch(err=>{
        res.status(500).json(err)
    })
    /*req.body.productList.map((doc,index)=>{
        MongoProduct.findById(doc.pid).exec().then(result=>{
            if(!result){
                return res.status(404).json({
                    message:'no product'
                })
            }
            if(index==0){
                const decoded =(req.body.isDefuser)?jwt.decode(req.headers.token):{};
                const order=new MongoOrder({
                    _id:new mongoose.Types.ObjectId(),
                    name:decoded.username||req.body.username,
                    phone:decoded.phone||req.body.phone,
                    address:decoded.address||req.body.address,
                    product:req.body.productList
                })
                order.save().then(docs=>{
                    res.status(201).json({
                        message:'order created',
                        orders:docs
                    });
                }).catch(err=>{
                    res.status(500).json(err)
                })
            }
        }).catch(err=>{
            res.status(500).json(err)
        })
    })*/
}
exports.order_update=(req,res,next)=>{
    const pid = req.params.oid;
    const option = {};
    for (const opt of req.body) {
        option[opt.key] = opt.value
    }
    MongoOrder.updateOne({ _id: pid }, { $set: option }).exec().then(result => {
        res.status(200).json({
            message: 'update success',
            data: result
        })
    }).catch(err => {
        res.status(500).json(err)
    })
}
exports.order_get_all=(req, res, next) => { //.populate('product')关联查询cate是当前表字段名,name为查询匹配的该字段
    const orderCount=(req.params.page-1)*5;//分页显示，当前为一页5条数据
    MongoOrder.find().skip(orderCount).limit(5).populate('product').exec().then(result => {
        if(result.length>0){
            writeCache(req,result)
            res.status(200).json(result)
        }else{
            res.status(203).json({
                message:'no order'
            })
        }
    }).catch(err=>{
        res.status(500).json(err)
    })
    /*MongoOrder.find().exec().then(result => {
        let collection=[];
        if(result.length>0){
            result.map(v=>{
                v.product.map((doc,index)=>{
                    MongoProduct.findById(doc.pid).exec().then(dos=>{
                        collection.push(dos);
                        if(index===v.product.length-1){//遍历至最后一条返回产品信息
                            res.status(200).json({
                                count:collection.length,
                                data:{
                                    userData:result,
                                    productList:collection
                                }
                            })
                        }
                    }).catch(err=>{
                        res.status(401).json(err)
                    })
                })
            })
        }else{
            res.status(401).json({
                message:'no order'
            })
        }
    }).catch(err=>{
        res.status(500).json(err)
    })*/
}
exports.order_getById=(req, res, next) => {
    MongoOrder.find({_id:req.params.oid}).populate('product').exec().then(result => {
        if(result.length>0){
            writeCache(req,result);
            res.status(200).json(result)
        }else{
            res.status(401).json({
                message:'no order'
            })
        }
    }).catch(err=>{
        res.status(500).json(err)
    })
}
exports.order_delete=(req, res, next) => {
    MongoOrder.deleteOne({_id:req.params.oid}).exec().then(result => {
        res.status(200).json({
            message: 'delete success'
        })
    }).catch(err=>{
        res.status(500).json(err)
    })
}